package com.llu.jackson.study;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.llu.jackson.study.bean.Dna;
import com.llu.jackson.study.bean.HealthWorker;
import com.llu.jackson.study.bean.Person;

import java.io.IOException;

public class TestJackSon {
    public static void main(String[] args) throws Exception {

//        HealthWorker healthWorker = new HealthWorker();
//        healthWorker.setId(1);
//        healthWorker.setName("RehamMuzzamil");
//        healthWorker.setQualification("MBBS");
//        healthWorker.setYearsOfExperience(1.5);
//
//        serialize(healthWorker);

        testDeserialize();

    }

    //test JAVA_LANG_OBJECT
    public static void testDefaultTyping() throws Exception {
        //JAVA_LANG_OBJECT
        Person p = new Person();
        p.age = 10;
        p.name = "Alice";
        p.object = new Dna();
        ObjectMapper mapper = new ObjectMapper();
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT);
        String json = mapper.writeValueAsString(p);
        System.out.println(json);
        Person p2 = mapper.readValue(json, Person.class);
        System.out.println(p2);

    }

    public static void testDeserialize() throws IOException {
        String json = "{\"age\":10,\"name\":\"Alice\",\"object\":[\"com.llu.jackson.study.bean.Dna\",{\"length\":100}]}";
        ObjectMapper mapper = new ObjectMapper();
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT);
        Person p2 = mapper.readValue(json, Person.class);
        System.out.println(p2);
    }


    // 序列化
    public static void serialize(HealthWorker healthWorker) throws IOException {

        ObjectMapper objectMapper = new ObjectMapper();
        // 添加自定义序列化器
        SimpleModule module = new SimpleModule();
        module.addSerializer(HealthWorker.class, new MyJackson());

        String json = objectMapper.writeValueAsString(healthWorker);
        System.out.println(json);
    }

    // 反序列化
    public static void deserialize(String json) throws IOException {

        ObjectMapper objectMapper = new ObjectMapper();
//        String healthWorkerJSON = "{\"id\":1,\"name\":\"RehamMuzzamil\",\"qualification\":\"MBBS\",\"yearsOfExperience\":1.5}";

        String healthWorkerJSON = "{\n" +
                "  \"id\" : 1,\n" +
                "  \"name\" : \"RehamMuzzamil\",\n" +
                "  \"qualification\" : \"MBBS\",\n" +
                "  \"years_of_experience\" :1.5\n" +
                "}";

        HealthWorker healthWorker = objectMapper.readValue(healthWorkerJSON, HealthWorker.class);
        System.out.println(healthWorker.getId());
        System.out.println(healthWorker.getName());
        System.out.println(healthWorker.getQualification());
        System.out.println(healthWorker.getYearsOfExperience());
    }
}
